﻿/*
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2009
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Configuration;
using System.Web.Configuration;
using DotNetNuke.Tests.UI.WatiN.Common;
using DotNetNuke.Tests.UI.WatiN.Utilities;
using Gallio.Framework.Pattern;
using System.IO;
using WatiN.Core;

namespace DotNetNuke.Tests.UI.WatiN.UpgradeTests
{
    public class UpgradeBase : TestBase
    {
        protected WatiNBase baseWatinObject;
        protected IE ieInstance;

        #region Private Members
        private string databasePath;
        private string siteZipFileName;
        private string upgradeZipFileName;
        #endregion

        protected UpgradeContext UpgradeContext
        {
            get 
            {
                UpgradeContext context = null;
                PatternTestInstanceState testState = PatternTestInstanceState.FromContext(TestContext);
                if (testState.TestArguments != null && testState.TestArguments.Length > 1)
                {
                    string version = testState.TestArguments[0] as string;
                    string type = testState.TestArguments[1] as string;
                    context = new UpgradeContext(version, type);
                }
                return context;
            }
        }

        protected virtual string ApplicationName
        {
            get
            {
               string appName = String.Format("DNN_{0}", UpgradeVersion.ToString(3).Replace(".", ""));
               return appName;
            }
        }

        protected override string SiteURL
        {
            get
            {
                return String.Format("http://localhost/{0}", ApplicationName);
            }
        }

        protected string PhysicalPath
        {
            get
            {
                string physicalPath = Path.Combine(TestEnvironment.WebsitePath, "UpgradeTests");
                physicalPath = Path.Combine(physicalPath, ApplicationName);
                //return (!IsUpgrade) ? physicalPath : String.Format("{0}_{1}", physicalPath, SiteType);
                physicalPath = String.Format("{0}_{1}", physicalPath, SiteType);
                return physicalPath;
            }
        }

        protected string DatabaseName
        {
            get
            {
                string _DatabaseName = String.Format("DNN_{0}_{1}", TestVersion.Replace(".", ""), SiteType);
                return _DatabaseName;

            }
        }

        protected string CapturePath
        {
            get
            {
                string physicalPath = Path.Combine(TestEnvironment.ScreenCapturePath, "UpgradeTests");
                physicalPath = Path.Combine(physicalPath, ApplicationName);
                return String.Format("{0}_{1}", physicalPath, SiteType);
            }
        }

        protected Version UpgradeVersion
        {
            get { return (UpgradeContext == null) ? null : UpgradeContext.UpgradeVersion; }
        }

        protected string SiteType
        {
            get { return (UpgradeContext == null) ? null : UpgradeContext.Type; }
        }

        #region SetUp Methods
        public void SetUpTest( )
        {
            //Make sure that the target folder is empty
            if (Directory.Exists(PhysicalPath))
            {
                Directory.Delete(PhysicalPath, true);
            }
            
            siteZipFileName = String.Format("{0}_{1}.zip", ApplicationName, SiteType);

            upgradeZipFileName = String.Format("DotNetNuke_{0}_{1}_Upgrade.zip", VersionType, TestVersion);

            //First Unzip Site Package to Website location
            ZipManager.ExtractZip(Path.Combine(TestEnvironment.PackagePath, siteZipFileName), Path.Combine(TestEnvironment.WebsitePath, "UpgradeTests"));

            //Next Unzip Upgrade Package to Website location
            ZipManager.ExtractZip(Path.Combine(TestEnvironment.PackagePath, upgradeZipFileName), PhysicalPath);

            //Next Create Website 
            SetUpWebSite(PhysicalPath, TestUsers.DBUser.UserName, TestUsers.DBUser.Password);
            if (UpgradeVersion < new Version("4.8.0"))
            {
                //Use classic pool
                IISManager.SetApplicationPool(ApplicationName, "Classic .NET AppPool");
            }


            //Attach Database
            databasePath = DatabaseManager.GetDataBaseFileName(TestContext, DatabaseName, ".mdf");
            File.Copy(Path.Combine(PhysicalPath, "App_Data\\Database.mdf"), databasePath, true);
            DatabaseManager.AttachDatabase(DatabaseName, databasePath);

            //Add User
            DatabaseManager.AddUser(DatabaseName, TestUsers.DBUser.UserName, TestUsers.DBUser.Password, new[] { "db_owner" });
        }

        protected void SetUpWebSite(string physicalPath, string userName, string password)
        {
            IISManager.RecycleApplicationPool(ApplicationName);
            IISManager.CreateIISApplication(ApplicationName, physicalPath);

            //Set web.config connection settings
            SetConnectionString(ApplicationName, DatabaseName, userName, password);
        }

        protected void SetConnectionString(string applicationPath, string databaseName, string userName, string password)
        {
            string connString = String.Format("Server={0};Database={1};uid={2};pwd={3};",
                                                                TestEnvironment.DatabaseServer,
                                                                databaseName,
                                                                userName,
                                                                password);

            Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/" + applicationPath);

            //Setup Connection String
            ConnectionStringsSection connectionStringsSection = configuration.GetSection("connectionStrings") as ConnectionStringsSection;
            ConnectionStringSettingsCollection connectionStrings = connectionStringsSection.ConnectionStrings;
            ConnectionStringSettings connectionString = connectionStrings["SiteSqlServer"];
            connectionString.ConnectionString = connString;

            AppSettingsSection appSettingsSection = configuration.GetSection("appSettings") as AppSettingsSection; ;
            appSettingsSection.Settings["SiteSqlServer"].Value = connString;

            configuration.Save();
        }
        #endregion

        #region TearDown Methods

        protected void TearDownTest()
        {
            //Make sure user is logged out
            ieInstance.GoTo(SiteURL + "/LogOff.aspx");

            //Shut down Ie
            WatiNUtil.CloseIEInstance(ieInstance);

            //Recycle IIS App Pool
            IISManager.RecycleApplicationPool(ApplicationName);

            //Drop Database
            DatabaseManager.DropDatabase(DatabaseName);
        }

        #endregion
    }
}
